package com.cheems.henau_doc_ai.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheems.henau_doc_ai.common.ErrorCode;
import com.cheems.henau_doc_ai.domain.User;
import com.cheems.henau_doc_ai.exception.BusinessException;
import com.cheems.henau_doc_ai.exception.ThrowUtils;
import com.cheems.henau_doc_ai.service.UserService;
import com.cheems.henau_doc_ai.mapper.UserMapper;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import jakarta.annotation.Resource;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
* @author lenovo
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-02-24 15:57:50
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Value("${heanu.app.app-id}")
    private String appid;

    @Value("${heanu.app.app-secret}")
    private String secret;

    @Resource
    private UserMapper userMapper;

    @Override
    public User login(String code) {
        //创建httpClient
        HttpClient httpClient = HttpClient.newHttpClient();
        String url = "https://oauth.henau.edu.cn/oauth2_server/access_token?appid="+appid+"&secret="+secret+"&code=" + code + "&grant_type=authorization_code";
        
        // 发送 GET 请求并处理响应
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .GET()
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            
            // 解析响应
            String responseBody = response.body();
            // 这里可以使用 JSON 解析库（如 Jackson 或 Gson）来解析 responseBody
            //获取access_token和henau_openid
            // 例如：

            JSONObject jsonObject = JSON.parseObject(responseBody);

            String accessToken = jsonObject.getJSONObject("data").getString("access_token");
            String henauOpenid = jsonObject.getJSONObject("data").getString("henau_openid");
            System.out.println("access_token: " + accessToken);
            System.out.println("henau_openid: " + henauOpenid);
            //请求获取用户信息
            String userInfoUrl = "https://oauth.henau.edu.cn/oauth2_server/userinfo?access_token="+accessToken+"&henau_openid="+henauOpenid;
            try {
                request = HttpRequest.newBuilder()
                        .uri(URI.create(userInfoUrl))
                        .GET()
                        .build();

                response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

                // 解析响应
                String responseBodyUser = response.body();
                // 这里可以使用 JSON 解析库（如 Jackson 或 Gson）来解析 responseBody
                //获取access_token和henau_openid
                // 例如：
                JSONObject jsonObjectUser = JSON.parseObject(responseBodyUser);

                String user_name = jsonObjectUser.getJSONObject("data").getString("user_name");
                String user_number = jsonObjectUser.getJSONObject("data").getString("user_number");

                // 根据 henau_number 查询用户是否存在
                User user = userMapper.selectOne(new QueryWrapper<User>().eq("henau_number", user_number));
                if (user == null) {
                    // 用户不存在，则插入新用户
                    user = new User();
                    user.setUserName(user_name);
                    user.setHenauNumber(user_number);
                    user.setHenauOpenid(henauOpenid);
                    userMapper.insert(user);
                } else {
                    // 用户存在，则更新用户信息
                    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("henau_openid", henauOpenid);
                    userMapper.update(user, updateWrapper);
                }

                //返回对象user
                return user;
            }
            catch (Exception e){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
    }
}




